<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>审稿流程订制</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

        .container {
            width: 80vw;
            height: 100vh;
            margin: 0 auto;
            padding: 20px;
            background-color: white;
            box-sizing: border-box;
            overflow-y: auto;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e0e0e0;
        }

        .header h1 {
            font-size: 28px;
            color: #2c3e50;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .header .icon {
            width: 24px;
            height: 24px;
            background-color: #3498db;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }

        .section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: #fafafa;
        }

        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .section-title .icon {
            width: 20px;
            height: 20px;
            background-color: #27ae60;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
        }

        .radio-group {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .radio-item {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .radio-item input[type="radio"] {
            width: 18px;
            height: 18px;
            accent-color: #e74c3c;
        }
        
        .radio-item input[type="radio"]:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .radio-item label {
            cursor: pointer;
            font-size: 16px;
        }
        
        .radio-item input[type="radio"]:disabled + label {
            opacity: 0.5;
            cursor: not-allowed;
            color: #999;
        }

        .dropdown-container {
            position: relative;
            margin-bottom: 20px;
        }

        .dropdown {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            background-color: white;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .dropdown:hover {
            border-color: #e74c3c;
        }

        .dropdown.open {
            border-color: #e74c3c;
        }

        .dropdown-options {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background-color: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            z-index: 1000;
            max-height: 200px;
            overflow-y: auto;
            display: none;
        }

        .dropdown-options.show {
            display: block;
        }

        .dropdown-option {
            padding: 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
        }

        .dropdown-option:hover {
            background-color: #f8f9fa;
        }

        .dropdown-option:last-child {
            border-bottom: none;
        }

        .selected-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 20px;
        }

        .tag {
            background-color: #e74c3c;
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .tag .remove {
            cursor: pointer;
            font-weight: bold;
        }

        .tag .remove:hover {
            color: #ffebee;
        }

        .confirm-btn {
            background-color: white;
            border: 2px solid #e74c3c;
            color: #e74c3c;
            padding: 12px 24px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
        }

        .confirm-btn:hover {
            background-color: #e74c3c;
            color: white;
        }

        .confirm-btn .icon {
            width: 16px;
            height: 16px;
            background-color: #27ae60;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 10px;
        }

        .process-selection {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .process-selection .radio-item {
            flex: 1;
        }

        .textarea-container {
            margin-bottom: 20px;
        }

        .textarea-container label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }

        .textarea {
            width: 100%;
            min-height: 120px;
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 16px;
            font-family: inherit;
            resize: vertical;
        }

        .run-btn {
            background-color: #95a5a6;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
        }

        .run-btn:hover:not(:disabled) {
            background-color: #7f8c8d;
        }

        .run-btn:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }

        .run-btn.update {
            background-color: #27ae60;
        }

        .run-btn.update:hover {
            background-color: #229954;
        }

        .flowchart-section {
            margin-top: 30px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background-color: white;
        }

        .flowchart {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 20px;
            margin-bottom: 20px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
        }

        .flowchart-node {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .node-circle {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .node-start {
            background-color: #27ae60;
        }

        .node-end {
            background-color: #e67e22;
        }

        .node-rect {
            background-color: #3498db;
            color: white;
            padding: 8px 16px;
            border-radius: 6px;
            text-align: center;
            min-width: 120px;
        }

        .arrow {
            width: 0;
            height: 0;
            border-left: 15px solid #34495e;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
        }

        .sequence-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .sequence-table th,
        .sequence-table td {
            border: 1px solid #e0e0e0;
            padding: 12px;
            text-align: left;
        }

        .sequence-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }

        .sequence-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        .hidden {
            display: none;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* BPMN流程图样式 */
        .bpmn-container {
            width: 100%;
            text-align: center;
            margin: 20px 0;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        .bpmn-svg {
            max-width: 100%;
            height: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: white;
        }

        .process-item {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 12px;
            background-color: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .process-header {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e0e0e0;
        }

        .process-name {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }

        .process-content {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .process-flowchart {
            flex: 3; /* 流程图占比 3 */
            min-height: 200px;
            max-height: 300px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 10px;
            background-color: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: auto; /* 大图可滚动 */
        }

        .process-sequence {
            flex: 2; /* 序列占比 2 */
            min-height: 200px;
            max-height: 300px;
            overflow-y: auto;
        }

        .sequence-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
            margin: 0;
        }

        .sequence-table th,
        .sequence-table td {
            border: 1px solid #e0e0e0;
            padding: 8px;
            text-align: left;
        }

        .sequence-table th {
            background-color: #f8f9fa;
            font-weight: bold;
            font-size: 11px;
        }

        .sequence-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        .flowchart-svg {
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
        }

        /* 让后端返回的SVG在容器内自适应缩放 */
        .process-flowchart svg {
            width: 100% !important;
            height: auto !important;
            max-height: 100%;
        }
        
        /* 序列和参数配置左右并行布局 */
        .sequence-and-params {
            display: flex;
            gap: 20px;
            margin-top: 15px;
            flex-direction: row; /* 确保左右布局 */
        }
        
        .sequence-container {
            flex: 3; /* 左侧流程序列表占比3 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background: #f9f9f9;
        }
        
        .params-container {
            flex: 2; /* 右侧参数配置占比2 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            background: #f9f9f9;
        }
        
        .param-row {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            gap: 10px;
        }
        
        .param-label {
            font-weight: bold;
            min-width: 120px;
        }
        
        .param-input-group {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .param-input {
            width: 80px;
            padding: 5px 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            text-align: center;
        }
        
        .param-unit {
            color: #666;
            font-size: 14px;
        }
        
        .param-confirm-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .param-confirm-btn:hover {
            background: #0056b3;
        }
        
        .param-confirm-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        /* 流程定制和工具库布局 */
        .workflow-customization-container {
            display: flex;
            gap: 20px;
            margin-top: 15px;
        }
        
        .workflow-customization-main {
            flex: 3; /* 左侧流程定制占比3 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            background: #f9f9f9;
        }
        
        .tool-library-container {
            flex: 2; /* 右侧工具库占比2 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 20px;
            background: #f9f9f9;
        }
        
        .tool-library-content {
            margin-top: 15px;
        }
        
        .tool-library-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 6px;
            max-height: 350px;
            overflow-y: auto;
        }
        
        .tool-item {
            padding: 8px 12px;
            background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
            border: 1px solid #e1bee7;
            border-radius: 12px;
            color: #4a4a4a;
            font-size: 12px;
            font-weight: 500;
            text-align: center;
            transition: all 0.2s ease;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            line-height: 1.3;
        }
        
        .tool-item:hover {
            background: linear-gradient(135deg, #bbdefb 0%, #e1bee7 100%);
            transform: translateY(-1px);
            box-shadow: 0 2px 6px rgba(0,0,0,0.15);
            border-color: #ba68c8;
        }
        
        /* 工具库滚动条样式（如果需要） */
        .tool-library-grid::-webkit-scrollbar {
            width: 4px;
        }
        
        .tool-library-grid::-webkit-scrollbar-track {
            background: #f8f9fa;
            border-radius: 2px;
        }
        
        .tool-library-grid::-webkit-scrollbar-thumb {
            background: #dee2e6;
            border-radius: 2px;
        }
        
        .tool-library-grid::-webkit-scrollbar-thumb:hover {
            background: #adb5bd;
        }
        
        /* 系统角色管理样式 */
        .role-management-container {
            display: flex;
            gap: 20px;
            margin-top: 15px;
        }
        
        .role-add-container {
            flex: 2; /* 左侧添加角色占比2 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 5px;
            background: #f9f9f9;
        }
        
        .role-list-container {
            flex: 3; /* 右侧角色列表占比3 */
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 5px;
            background: #f9f9f9;
        }
        
        
        .role-add-form {
            margin-top: 5px;
        }
        
        .input-group {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 5px;
        }
        
        .add-btn {
            width: 30px;
            height: 30px;
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .add-btn:hover {
            background: linear-gradient(135deg, #45a049 0%, #3d8b40 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .role-input {
            flex: 1;
            padding: 5px 10px;
            border: 2px solid #e0e0e0;
            border-radius: 20px;
            font-size: 12px;
            outline: none;
            transition: all 0.3s ease;
        }
        
        .role-input:focus {
            border-color: #4CAF50;
            box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.1);
        }
        
        .confirm-btn {
            padding: 5px 15px;
            background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%);
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .confirm-btn:hover {
            background: linear-gradient(135deg, #1976D2 0%, #1565C0 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .role-message {
            margin-top: 5px;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
            min-height: 16px;
        }
        
        .role-message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .role-message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .role-list {
            margin-top: 5px;
            max-height: 60px;
            overflow-y: auto;
            display: flex;
            flex-wrap: wrap;
            gap: 3px;
        }
        
        .role-item {
            display: inline-flex;
            align-items: center;
            gap: 2px;
            padding: 2px 6px;
            background: linear-gradient(135deg, #e8f5e8 0%, #f0f8f0 100%);
            border: 1px solid #c8e6c9;
            border-radius: 12px;
            transition: all 0.2s ease;
            white-space: nowrap;
        }
        
        .role-item:hover {
            background: linear-gradient(135deg, #d4edda 0%, #e8f5e8 100%);
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .role-name {
            font-size: 10px;
            font-weight: 500;
            color: #2e7d32;
        }
        
        .role-delete-btn {
            width: 12px;
            height: 12px;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 50%;
            font-size: 8px;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .role-delete-btn:hover {
            background: #d32f2f;
            transform: scale(1.1);
        }
        
        .empty-roles {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 10px;
            font-size: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>
                <span class="icon">@</span>
                流程定制系统
            </h1>
        </div>

        <!-- 系统角色定制 -->
        <div class="section" id="roleManagementSection">
            <div class="role-management-container">
                <!-- 左侧：添加角色 -->
                <div class="role-add-container">
                    <div class="section-title">
                        <span class="icon">👤</span>
                        系统角色定制
                    </div>
                    <div class="role-add-form">
                        <div class="input-group">
                            <button class="add-btn" id="addRoleBtn">+</button>
                            <input type="text" id="roleNameInput" placeholder="请输入角色名称..." class="role-input">
                            <button class="confirm-btn" id="confirmRoleBtn">确定</button>
                        </div>
                        <div id="roleMessage" class="role-message"></div>
                    </div>
                </div>
                
                <!-- 右侧：角色列表 -->
                <div class="role-list-container">
                    <div class="section-title">
                        <span class="icon">📋</span>
                        已定制角色
                    </div>
                    <div class="role-list" id="roleList">
                        <!-- 动态加载角色列表 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 系统阶段定制 -->
        <div class="section" id="workflowStageSection">
            <div class="role-management-container">
                <!-- 左侧：添加阶段 -->
                <div class="role-add-container">
                    <div class="section-title">
                        <span class="icon">📋</span>
                        系统阶段定制
                    </div>
                    <div class="role-add-form">
                        <div class="input-group">
                            <button class="add-btn" id="addStageBtn">+</button>
                            <input type="text" id="stageNameInput" placeholder="请输入阶段名称..." class="role-input">
                            <select id="stageRoleSelect" class="role-input" style="margin-left: 5px;">
                                <option value="">请选择角色</option>
                            </select>
                            <button class="confirm-btn" id="confirmStageBtn">确定</button>
                        </div>
                        <div id="stageMessage" class="role-message"></div>
                    </div>
                </div>
                
                <!-- 右侧：阶段列表 -->
                <div class="role-list-container">
                    <div class="section-title">
                        <span class="icon">📊</span>
                        已定制阶段
                    </div>
                    <div class="role-list" id="stageList">
                        <!-- 动态加载阶段列表 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 审稿结果定制 -->
        <div class="section" id="statusSection">
            <div class="role-management-container">
                <!-- 左侧：选择阶段并定制审稿结果 -->
                <div class="role-add-container">
                    <div class="section-title">
                        <span class="icon">🔄</span>
                        审稿结果定制
                    </div>
                    <div class="role-add-form">
                        <div class="input-group" style="margin-bottom: 10px;">
                            <label style="font-size: 12px; color: #666; margin-right: 5px;">选择阶段:</label>
                            <select id="stageSelectForStatus" class="role-input" style="flex: 1;">
                                <option value="">请选择阶段</option>
                            </select>
                        </div>
                        <div class="input-group">
                            <button class="add-btn" id="addStatusBtn">+</button>
                            <input type="text" id="statusNameInput" placeholder="请输入审稿结果..." class="role-input">
                            <button class="confirm-btn" id="confirmStatusBtn">确定</button>
                        </div>
                        <div id="statusMessage" class="role-message"></div>
                    </div>
                </div>
                
                <!-- 右侧：已定制审稿结果列表 -->
                <div class="role-list-container">
                    <div class="section-title">
                        <span class="icon">📈</span>
                        已定制审稿结果
                    </div>
                    <div class="role-list" id="statusList">
                        <!-- 动态加载审稿结果列表 -->
                    </div>
                </div>
            </div>
        </div>

        <!-- 审稿流程定制 -->
        <div class="section" id="processCustomizationSection">
            <div class="section-title">
                <span class="icon">✓</span>
                审稿流程定制
            </div>
            <p style="margin-bottom: 15px;">请选择要重新订制全流程还是局部更改流程:</p>
            <div class="radio-group">
                <div class="radio-item">
                    <input type="radio" id="partial" name="processType" value="partial" checked>
                    <label for="partial">局部更改流程</label>
                </div>
                <div class="radio-item">
                    <input type="radio" id="full" name="processType" value="full">
                    <label for="full">重新定制全流程</label>
                </div>
            </div>
        </div>


        <!-- 局部更改流程 - 已定制流程选择 -->
        <div class="section" id="partialSection">
            <div class="section-title">
                <span class="icon">✓</span>
                所有已定制流程
            </div>
            <div id="existingProcesses">
                <!-- 动态加载现有流程 -->
            </div>
        </div>

        <!-- 重新定制全流程 - 流程选择 -->
        <div class="section hidden" id="fullSection">
            <div class="section-title">
                <span class="icon">✓</span>
                流程选择
            </div>
            <p style="margin-bottom: 15px;">请选择你希望定制的所有流程:</p>
            <div class="dropdown-container">
                <div class="dropdown" id="processDropdown">
                    <span>Choose an option</span>
                    <span>▼</span>
                </div>
                <div class="dropdown-options" id="processOptions">
                    <!-- 动态加载 -->
                </div>
            </div>
            <div class="selected-tags" id="selectedTags">
                <!-- 动态生成选中的标签 -->
            </div>
            <button class="confirm-btn" id="confirmBtn" style="display: none;">
                <span class="icon">✓</span>
                确认定制工作流
            </button>
        </div>

        <!-- 当前定制流程选择 -->
        <div class="section hidden" id="currentProcessSection">
            <div class="section-title">
                <span class="icon">✓</span>
                当前定制流程
            </div>
            <p style="margin-bottom: 15px;">请选择当前要定制的流程:</p>
            <div class="radio-group" id="currentProcessSelection">
                <!-- 动态生成 -->
            </div>
        </div>

        <!-- 业务操作界面 -->
        <div class="section" id="businessOperationSection">
            <div class="workflow-customization-container">
                <!-- 左侧：流程定制操作 -->
                <div class="workflow-customization-main">
                    <div class="section-title">
                        <span class="icon">✓</span>
                        流程定制操作
                    </div>
                    <p style="margin-bottom: 15px;">请选择当前要定制的流程:</p>
                    <div class="radio-group" id="processSelectionRadio">
                        <!-- 动态生成流程选择radio -->
                    </div>
                    <div class="textarea-container" style="margin-top: 20px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: bold;">请给出对应的流程描述:</label>
                        <textarea class="textarea" id="processDescription" placeholder="请输入流程描述..."></textarea>
                    </div>
                    <button class="run-btn" id="runBtn">运行</button>
                </div>
                
                <!-- 右侧：工具库展示 -->
                <div class="tool-library-container">
                    <div class="section-title">
                        <span class="icon">🔧</span>
                        流程工具库
                    </div>
                    <div class="tool-library-content">
                        <div class="tool-library-grid">
                            <div class="tool-item">1. 选择稿件</div>
                            <div class="tool-item">2. 获取初审意见</div>
                            <div class="tool-item">3. 发送初审邮件</div>
                            <div class="tool-item">4. 推荐责编</div>
                            <div class="tool-item">5. 选择外审专家</div>
                            <div class="tool-item">6. 接收评审意见</div>
                            <div class="tool-item">7. 汇总评审意见</div>
                            <div class="tool-item">8. 发送外审邮件</div>
                            <div class="tool-item">9. 生成副终审意见</div>
                            <div class="tool-item">10. 发送副终审邮件</div>
                            <div class="tool-item">11. 生成终审意见</div>
                            <div class="tool-item">12. 发送终审邮件</div>
                            <div class="tool-item">13. 等待外审专家同意审稿</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 流程图和序列显示 -->
        <div class="flowchart-section hidden" id="resultSection">
            <div class="section-title">
                <span class="icon">📊</span>
                流程图
            </div>
            <div class="bpmn-container" id="bpmnContainer">
                <!-- BPMN流程图将在这里显示 -->
            </div>

            <div class="section-title">
                <span class="icon">📋</span>
                流程序列表
            </div>
            <table class="sequence-table" id="sequenceTable">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>now_state</th>
                        <th>next_state</th>
                        <th>condition</th>
                        <th>parameter</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 动态生成表格内容 -->
                </tbody>
            </table>
            
            
            <!-- 保存模型模块 -->
            <div id="saveModelModule" style="display: none; margin-top: 20px; padding: 15px; border: 1px solid #ddd; border-radius: 5px; background-color: #e8f5e8;">
                <h4>保存模型</h4>
                <p>确认将当前生成的模型和流程数据保存到数据库？</p>
                <button id="saveModelBtn" onclick="saveModel()" style="background-color: #28a745; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
                    确认保存模型
                </button>
                <div id="saveStatus" style="margin-top: 10px;"></div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let selectedProcesses = [];
        let currentProcessType = 'partial';
        let isGenerating = false;
        let selectedProcessName = null;
        let processModel = null; // 存储当前模型
        let feedbackHistory = []; // 存储反馈历史
        let isFirstGeneration = true; // 跟踪是否为首次生成

        // DOM 元素
        const processTypeRadios = document.querySelectorAll('input[name="processType"]');
        const partialSection = document.getElementById('partialSection');
        const fullSection = document.getElementById('fullSection');
        const currentProcessSection = document.getElementById('currentProcessSection');
        const processDropdown = document.getElementById('processDropdown');
        const processOptions = document.getElementById('processOptions');
        const selectedTags = document.getElementById('selectedTags');
        const confirmBtn = document.getElementById('confirmBtn');
        const currentProcessSelection = document.getElementById('currentProcessSelection');
        const processDescription = document.getElementById('processDescription');
        const runBtn = document.getElementById('runBtn');
        const resultSection = document.getElementById('resultSection');
        const bpmnContainer = document.getElementById('bpmnContainer');
        const sequenceTable = document.getElementById('sequenceTable').getElementsByTagName('tbody')[0];
        const existingProcesses = document.getElementById('existingProcesses');
        const businessOperationSection = document.getElementById('businessOperationSection');
        const processSelectionRadio = document.getElementById('processSelectionRadio');

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeEventListeners();
            
            // 确保结果区域在页面加载时是隐藏的
            resultSection.classList.add('hidden');
            
            // 默认加载局部更改流程
            loadExistingProcesses();
            loadProcessSelectionRadio();
            // 加载角色管理功能
            loadRoles();
            initializeRoleManagement();
            // 加载阶段管理功能
            loadWorkflowStages();
            initializeWorkflowStageManagement();
            // 加载状态管理功能
            loadStatuses();
            initializeStatusManagement();
        });

        // 事件监听器
        function initializeEventListeners() {
            // 流程类型选择
            processTypeRadios.forEach(radio => {
                radio.addEventListener('change', handleProcessTypeChange);
            });

            // 下拉菜单
            processDropdown.addEventListener('click', toggleDropdown);
            document.addEventListener('click', closeDropdown);

            // 确认按钮
            confirmBtn.addEventListener('click', confirmProcessSelection);

            // 运行按钮
            runBtn.addEventListener('click', runProcess);

            // 现有流程选择
            document.addEventListener('change', function(e) {
                if (e.target.name === 'existingProcess') {
                    handleExistingProcessChange(e.target.value);
                }
                if (e.target.name === 'currentProcess') {
                    handleCurrentProcessChange(e.target.value);
                }
                if (e.target.name === 'processSelection') {
                    handleProcessSelectionChange(e.target.value);
                }
            });
        }

        // 处理流程类型变化
        function handleProcessTypeChange(e) {
            currentProcessType = e.target.value;
            
            // 隐藏所有下方内容
            partialSection.classList.add('hidden');
            fullSection.classList.add('hidden');
            currentProcessSection.classList.add('hidden');
            businessOperationSection.classList.add('hidden');
            resultSection.classList.add('hidden');
            
            // 清空结果区域内容，避免显示空内容
            bpmnContainer.innerHTML = '';
            sequenceTable.innerHTML = '';
            
            // 重置按钮状态和文本框内容
            resetProcessState();
            
            // 根据选择显示对应内容
            if (currentProcessType === 'partial') {
                partialSection.classList.remove('hidden');
                businessOperationSection.classList.remove('hidden');
                loadExistingProcesses();
                loadProcessSelectionRadio();
            } else if (currentProcessType === 'full') {
                fullSection.classList.remove('hidden');
                loadAvailableProcesses();
            }
        }

        // 重置流程状态
        function resetProcessState() {
            // 重置按钮状态
            runBtn.textContent = '运行';
            runBtn.classList.remove('update');
            runBtn.disabled = false;
            
            // 清空文本框内容
            processDescription.value = '';
            
            // 重置全局状态变量
            selectedProcessName = null;
            processModel = null;
            feedbackHistory = [];
            isFirstGeneration = true;
            isGenerating = false;
            
            // 启用所有阶段选择
            enableAllProcessSelections();
        }

        // 禁用所有阶段选择
        function disableAllProcessSelections() {
            // 禁用局部更改流程的选择
            const processSelections = document.querySelectorAll('input[name="processSelection"]');
            processSelections.forEach(radio => {
                radio.disabled = true;
            });
            
            // 禁用重新定制全流程的选择
            const currentProcessSelections = document.querySelectorAll('input[name="currentProcess"]');
            currentProcessSelections.forEach(radio => {
                radio.disabled = true;
            });
        }

        // 启用所有阶段选择
        function enableAllProcessSelections() {
            // 启用局部更改流程的选择
            const processSelections = document.querySelectorAll('input[name="processSelection"]');
            processSelections.forEach(radio => {
                radio.disabled = false;
            });
            
            // 启用重新定制全流程的选择
            const currentProcessSelections = document.querySelectorAll('input[name="currentProcess"]');
            currentProcessSelections.forEach(radio => {
                radio.disabled = false;
            });
        }

        // 切换下拉菜单
        function toggleDropdown(e) {
            e.stopPropagation();
            processOptions.classList.toggle('show');
            processDropdown.classList.toggle('open');
        }

        // 关闭下拉菜单
        function closeDropdown() {
            processOptions.classList.remove('show');
            processDropdown.classList.remove('open');
        }

        // 加载现有流程
        async function loadExistingProcesses() {
            try {
                const response = await fetch('/api/processes/existing');
                const processes = await response.json();
                
                existingProcesses.innerHTML = '';
                
                if (processes.length === 0) {
                    existingProcesses.innerHTML = `
                        <div style="text-align: center; padding: 40px; color: #666;">
                            <h3>当前没有已定制流程</h3>
                            <p>请先进行流程定制操作</p>
                        </div>
                    `;
                } else {
                    processes.forEach((process, index) => {
                        const processItem = document.createElement('div');
                        processItem.className = 'process-item';
                        
                        // 生成序列表格HTML
                        const sequenceTableHtml = generateSequenceTable(process.sequence_data);
                        
                        processItem.innerHTML = `
                            <div class="process-header">
                                <div class="process-name">${process.workflow}</div>
                            </div>
                            <div class="process-content">
                                <div class="process-flowchart">
                                    ${process.flowchart_svg || '<div>流程图加载失败</div>'}
                                </div>
                                <div class="process-sequence">
                                    <h4 style="margin-bottom: 10px; color: #2c3e50;">流程序列</h4>
                                    ${sequenceTableHtml}
                                </div>
                            </div>
                        `;
                        existingProcesses.appendChild(processItem);
                    });
                }
            } catch (error) {
                console.error('加载现有流程失败:', error);
                existingProcesses.innerHTML = `
                    <div style="text-align: center; padding: 40px; color: #e74c3c;">
                        <h3>加载失败</h3>
                        <p>请检查数据库连接</p>
                    </div>
                `;
            }
        }

        // 生成序列表格HTML
        function generateSequenceTable(sequenceData) {
            if (!sequenceData || sequenceData.length === 0) {
                return '<div>暂无序列数据</div>';
            }
            
            let tableHtml = `
                <table class="sequence-table">
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>now_state</th>
                            <th>next_state</th>
                            <th>condition</th>
                            <th>parameter</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            sequenceData.forEach(row => {
                tableHtml += `
                    <tr>
                        <td>${row.id || ''}</td>
                        <td>${row.now_state || ''}</td>
                        <td>${row.next_state || ''}</td>
                        <td>${typeof row.condition === 'object' ? JSON.stringify(row.condition) : (row.condition || '无')}</td>
                        <td>${typeof row.parameter === 'object' ? JSON.stringify(row.parameter) : (row.parameter || '无参数')}</td>
                    </tr>
                `;
            });
            
            tableHtml += `
                    </tbody>
                </table>
            `;
            
            return tableHtml;
        }

        // 加载流程选择radio
        async function loadProcessSelectionRadio() {
            try {
                const response = await fetch('/api/processes/existing');
                const processes = await response.json();
                
                processSelectionRadio.innerHTML = '';
                
                if (processes.length === 0) {
                    processSelectionRadio.innerHTML = `
                        <div style="text-align: center; padding: 20px; color: #666;">
                            <p>暂无可用流程</p>
                        </div>
                    `;
                } else {
                    processes.forEach((process, index) => {
                        const radioItem = document.createElement('div');
                        radioItem.className = 'radio-item';
                        radioItem.innerHTML = `
                            <input type="radio" id="process_${index}" name="processSelection" value="${process.workflow}" ${index === 0 ? 'checked' : ''}>
                            <label for="process_${index}">${process.workflow}</label>
                        `;
                        processSelectionRadio.appendChild(radioItem);
                    });
                }
            } catch (error) {
                console.error('加载流程选择失败:', error);
                processSelectionRadio.innerHTML = `
                    <div style="text-align: center; padding: 20px; color: #e74c3c;">
                        <p>加载失败</p>
                    </div>
                `;
            }
        }

        // 加载可用流程
        async function loadAvailableProcesses() {
            try {
                const response = await fetch('/api/processes/available');
                const processes = await response.json();
                
                processOptions.innerHTML = '';
                processes.forEach(process => {
                    const option = document.createElement('div');
                    option.className = 'dropdown-option';
                    option.textContent = process.name;
                    option.addEventListener('click', () => selectProcessForFull(process));
                    processOptions.appendChild(option);
                });
            } catch (error) {
                console.error('加载可用流程失败:', error);
            }
        }

        // 角色管理功能
        async function loadRoles() {
            try {
                const response = await fetch('/api/roles');
                const roles = await response.json();
                
                const roleList = document.getElementById('roleList');
                roleList.innerHTML = '';
                
                if (roles.length === 0) {
                    roleList.innerHTML = `
                        <div class="empty-roles">
                            <p>暂无已定制角色</p>
                        </div>
                    `;
                } else {
                    roles.forEach(role => {
                        const roleItem = document.createElement('div');
                        roleItem.className = 'role-item';
                        roleItem.innerHTML = `
                            <span class="role-name">${role.name}</span>
                            <button class="role-delete-btn" onclick="deleteRole(${role.id})" title="删除角色">×</button>
                        `;
                        roleList.appendChild(roleItem);
                    });
                }
            } catch (error) {
                console.error('加载角色列表失败:', error);
                const roleList = document.getElementById('roleList');
                roleList.innerHTML = `
                    <div class="empty-roles">
                        <p>加载角色失败</p>
                    </div>
                `;
            }
        }

        function initializeRoleManagement() {
            const addRoleBtn = document.getElementById('addRoleBtn');
            const confirmRoleBtn = document.getElementById('confirmRoleBtn');
            const roleNameInput = document.getElementById('roleNameInput');

            // 添加角色按钮点击事件
            addRoleBtn.addEventListener('click', function() {
                roleNameInput.focus();
            });

            // 确定按钮点击事件
            confirmRoleBtn.addEventListener('click', addRole);

            // 输入框回车事件
            roleNameInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    addRole();
                }
            });
        }

        async function addRole() {
            const roleNameInput = document.getElementById('roleNameInput');
            const roleMessage = document.getElementById('roleMessage');
            const roleName = roleNameInput.value.trim();

            if (!roleName) {
                showRoleMessage('请输入角色名称', 'error');
                return;
            }

            try {
                const response = await fetch('/api/roles', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ name: roleName })
                });

                const result = await response.json();

                if (result.success) {
                    showRoleMessage(result.message, 'success');
                    roleNameInput.value = '';
                    loadRoles(); // 重新加载角色列表
                } else {
                    showRoleMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('添加角色失败:', error);
                showRoleMessage('添加角色失败，请重试', 'error');
            }
        }

        async function deleteRole(roleId) {
            if (!confirm('确定要删除这个角色吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/roles/${roleId}`, {
                    method: 'DELETE'
                });

                const result = await response.json();

                if (result.success) {
                    showRoleMessage(result.message, 'success');
                    loadRoles(); // 重新加载角色列表
                } else {
                    showRoleMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('删除角色失败:', error);
                showRoleMessage('删除角色失败，请重试', 'error');
            }
        }

        function showRoleMessage(message, type) {
            const roleMessage = document.getElementById('roleMessage');
            roleMessage.textContent = message;
            roleMessage.className = `role-message ${type}`;
            
            // 3秒后清除消息
            setTimeout(() => {
                roleMessage.textContent = '';
                roleMessage.className = 'role-message';
            }, 3000);
        }

        // 系统阶段管理功能
        async function loadWorkflowStages() {
            try {
                const response = await fetch('/api/workflow-stages');
                const stages = await response.json();
                
                const stageList = document.getElementById('stageList');
                stageList.innerHTML = '';
                
                if (stages.length === 0) {
                    stageList.innerHTML = `
                        <div class="empty-roles">
                            <p>暂无已定制阶段</p>
                        </div>
                    `;
                } else {
                    stages.forEach(stage => {
                        const stageItem = document.createElement('div');
                        stageItem.className = 'role-item';
                        stageItem.innerHTML = `
                            <span class="role-name">${stage.name}：${stage.role || '未分配角色'}</span>
                            <button class="role-delete-btn" onclick="deleteWorkflowStage(${stage.id})" title="删除阶段">×</button>
                        `;
                        stageList.appendChild(stageItem);
                    });
                }
            } catch (error) {
                console.error('加载阶段列表失败:', error);
                const stageList = document.getElementById('stageList');
                stageList.innerHTML = `
                    <div class="empty-roles">
                        <p>加载阶段失败</p>
                    </div>
                `;
            }
        }

        function initializeWorkflowStageManagement() {
            const addStageBtn = document.getElementById('addStageBtn');
            const confirmStageBtn = document.getElementById('confirmStageBtn');
            const stageNameInput = document.getElementById('stageNameInput');
            const stageRoleSelect = document.getElementById('stageRoleSelect');

            // 加载角色选项
            loadRoleOptions();

            // 添加阶段按钮点击事件
            addStageBtn.addEventListener('click', function() {
                stageNameInput.focus();
            });

            // 确定按钮点击事件
            confirmStageBtn.addEventListener('click', addWorkflowStage);

            // 输入框回车事件
            stageNameInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    addWorkflowStage();
                }
            });
        }

        // 加载角色选项到下拉框
        async function loadRoleOptions() {
            try {
                const response = await fetch('/api/roles');
                const roles = await response.json();
                const stageRoleSelect = document.getElementById('stageRoleSelect');
                
                // 清空现有选项（保留第一个提示选项）
                stageRoleSelect.innerHTML = '<option value="">请选择角色</option>';
                
                // 添加角色选项
                roles.forEach(role => {
                    const option = document.createElement('option');
                    option.value = role.name;
                    option.textContent = role.name;
                    stageRoleSelect.appendChild(option);
                });
            } catch (error) {
                console.error('加载角色选项失败:', error);
            }
        }

        async function addWorkflowStage() {
            const stageNameInput = document.getElementById('stageNameInput');
            const stageRoleSelect = document.getElementById('stageRoleSelect');
            const stageMessage = document.getElementById('stageMessage');
            const stageName = stageNameInput.value.trim();
            const stageRole = stageRoleSelect.value.trim();

            if (!stageName) {
                showStageMessage('请输入阶段名称', 'error');
                return;
            }

            if (!stageRole) {
                showStageMessage('请选择角色', 'error');
                return;
            }

            try {
                const response = await fetch('/api/workflow-stages', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        name: stageName,
                        role: stageRole
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showStageMessage(result.message, 'success');
                    stageNameInput.value = '';
                    stageRoleSelect.value = '';
                    loadWorkflowStages(); // 重新加载阶段列表
                } else {
                    showStageMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('添加阶段失败:', error);
                showStageMessage('添加阶段失败，请重试', 'error');
            }
        }

        async function deleteWorkflowStage(stageId) {
            if (!confirm('确定要删除这个阶段吗？')) {
                return;
            }

            try {
                const response = await fetch(`/api/workflow-stages/${stageId}`, {
                    method: 'DELETE'
                });

                const result = await response.json();

                if (result.success) {
                    showStageMessage(result.message, 'success');
                    loadWorkflowStages(); // 重新加载阶段列表
                } else {
                    showStageMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('删除阶段失败:', error);
                showStageMessage('删除阶段失败，请重试', 'error');
            }
        }

        function showStageMessage(message, type) {
            const stageMessage = document.getElementById('stageMessage');
            stageMessage.textContent = message;
            stageMessage.className = `role-message ${type}`;
            
            // 3秒后清除消息
            setTimeout(() => {
                stageMessage.textContent = '';
                stageMessage.className = 'role-message';
            }, 3000);
        }

        // 审稿结果管理功能
        async function loadStatuses() {
            try {
                const response = await fetch('/api/workflow-stages');
                const stages = await response.json();
                
                const statusList = document.getElementById('statusList');
                statusList.innerHTML = '';
                
                if (stages.length === 0) {
                    statusList.innerHTML = `
                        <div class="empty-roles">
                            <p>暂无已定制审稿结果</p>
                        </div>
                    `;
                } else {
                    stages.forEach(stage => {
                        if (stage.status) {
                            const statusItem = document.createElement('div');
                            statusItem.className = 'role-item';
                            statusItem.innerHTML = `
                                <span class="role-name">${stage.name}：${stage.status}</span>
                                <button class="role-delete-btn" onclick="clearStageStatus(${stage.id})" title="清空审稿结果">×</button>
                            `;
                            statusList.appendChild(statusItem);
                        }
                    });
                    
                    // 如果没有审稿结果，显示提示
                    if (statusList.children.length === 0) {
                        statusList.innerHTML = `
                            <div class="empty-roles">
                                <p>暂无已定制审稿结果</p>
                            </div>
                        `;
                    }
                }
            } catch (error) {
                console.error('加载审稿结果列表失败:', error);
                const statusList = document.getElementById('statusList');
                statusList.innerHTML = `
                    <div class="empty-roles">
                        <p>加载审稿结果列表失败</p>
                    </div>
                `;
            }
        }

        function initializeStatusManagement() {
            const addStatusBtn = document.getElementById('addStatusBtn');
            const confirmStatusBtn = document.getElementById('confirmStatusBtn');
            const statusNameInput = document.getElementById('statusNameInput');
            const stageSelectForStatus = document.getElementById('stageSelectForStatus');

            // 加载阶段选项
            loadStageOptionsForStatus();

            // 添加状态按钮点击事件
            addStatusBtn.addEventListener('click', function() {
                statusNameInput.focus();
            });

            // 确定按钮点击事件
            confirmStatusBtn.addEventListener('click', addStatus);

            // 输入框回车事件
            statusNameInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    addStatus();
                }
            });
        }

        // 加载阶段选项到下拉框
        async function loadStageOptionsForStatus() {
            try {
                const response = await fetch('/api/workflow-stages');
                const stages = await response.json();
                const stageSelectForStatus = document.getElementById('stageSelectForStatus');
                
                // 清空现有选项（保留第一个提示选项）
                stageSelectForStatus.innerHTML = '<option value="">请选择阶段</option>';
                
                // 添加阶段选项
                stages.forEach(stage => {
                    const option = document.createElement('option');
                    option.value = stage.id;
                    option.textContent = stage.name;
                    stageSelectForStatus.appendChild(option);
                });
            } catch (error) {
                console.error('加载阶段选项失败:', error);
            }
        }

        async function addStatus() {
            const statusNameInput = document.getElementById('statusNameInput');
            const stageSelectForStatus = document.getElementById('stageSelectForStatus');
            const statusMessage = document.getElementById('statusMessage');
            const statusName = statusNameInput.value.trim();
            const stageId = stageSelectForStatus.value;

            if (!stageId) {
                showStatusMessage('请选择阶段', 'error');
                return;
            }

            if (!statusName) {
                showStatusMessage('请输入审稿结果', 'error');
                return;
            }

            try {
                const response = await fetch('/api/workflow-stages/update-status', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        stageId: parseInt(stageId),
                        status: statusName
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showStatusMessage(result.message, 'success');
                    statusNameInput.value = '';
                    loadStatuses(); // 重新加载审稿结果列表
                } else {
                    showStatusMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('添加审稿结果失败:', error);
                showStatusMessage('添加审稿结果失败，请重试', 'error');
            }
        }

        async function clearStageStatus(stageId) {
            if (!confirm('确定要清空这个阶段的审稿结果吗？')) {
                return;
            }

            try {
                const response = await fetch('/api/workflow-stages/clear-status', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ stageId: stageId })
                });

                const result = await response.json();

                if (result.success) {
                    showStatusMessage(result.message, 'success');
                    loadStatuses(); // 重新加载审稿结果列表
                } else {
                    showStatusMessage(result.message, 'error');
                }
            } catch (error) {
                console.error('清空审稿结果失败:', error);
                showStatusMessage('清空审稿结果失败，请重试', 'error');
            }
        }

        function showStatusMessage(message, type) {
            const statusMessage = document.getElementById('statusMessage');
            statusMessage.textContent = message;
            statusMessage.className = `role-message ${type}`;
            
            // 3秒后清除消息
            setTimeout(() => {
                statusMessage.textContent = '';
                statusMessage.className = 'role-message';
            }, 3000);
        }

        // 选择流程（全流程定制）
        function selectProcessForFull(process) {
            if (!selectedProcesses.find(p => p.id == process.id)) {
                selectedProcesses.push(process);
                updateSelectedTags();
                updateConfirmButton();
            }
            closeDropdown();
        }

        // 更新选中标签
        function updateSelectedTags() {
            selectedTags.innerHTML = '';
            selectedProcesses.forEach(process => {
                const tag = document.createElement('div');
                tag.className = 'tag';
                tag.innerHTML = `
                    ${process.name}
                    <span class="remove" onclick="removeProcess('${process.id}')">×</span>
                `;
                selectedTags.appendChild(tag);
            });
        }

        // 移除流程
        function removeProcess(processId) {
            selectedProcesses = selectedProcesses.filter(p => p.id != processId);
            updateSelectedTags();
            updateConfirmButton();
        }

        // 更新确认按钮
        function updateConfirmButton() {
            if (selectedProcesses.length > 0) {
                confirmBtn.style.display = 'flex';
            } else {
                confirmBtn.style.display = 'none';
            }
        }

        // 确认流程选择
        async function confirmProcessSelection() {
            if (selectedProcesses.length === 0) return;
            
            // 更新数据库中的工作流配置
            const workflowNames = selectedProcesses.map(p => p.name);
            try {
                const response = await fetch('/api/workflow-config/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        selectedStageNames: workflowNames
                    })
                });
                
                const result = await response.json();
                if (result.success) {
                    // 获取更新后的工作流配置
                    await loadWorkflowConfig();
                    
                    // 重置流程状态
                    resetProcessState();
                    
                    // 显示流程定制界面（与局部更改流程相同）
                    businessOperationSection.classList.remove('hidden');
                    
                    // 更新流程选择，显示用户确认定制的阶段
                    updateProcessSelectionRadio();
                } else {
                    alert('更新工作流配置失败: ' + result.message);
                }
            } catch (error) {
                console.error('更新工作流配置失败:', error);
                alert('更新工作流配置失败');
            }
        }

        // 加载工作流配置
        async function loadWorkflowConfig() {
            try {
                const response = await fetch('/api/workflow-config');
                const configs = await response.json();
                
                // 只显示enable为true的流程
                const enabledWorkflows = configs.filter(config => config.enable);
                
                // 更新当前流程选择，只显示启用的流程
                currentProcessSelection.innerHTML = '';
                enabledWorkflows.forEach((config, index) => {
                    const radioItem = document.createElement('div');
                    radioItem.className = 'radio-item';
                    radioItem.innerHTML = `
                        <input type="radio" id="current_${index}" name="currentProcess" value="${config.name}" ${index === 0 ? 'checked' : ''}>
                        <label for="current_${index}">${config.name}</label>
                    `;
                    currentProcessSelection.appendChild(radioItem);
                });
            } catch (error) {
                console.error('加载工作流配置失败:', error);
            }
        }

        // 更新当前流程选择
        function updateCurrentProcessSelection() {
            // 这个函数现在由loadWorkflowConfig处理
            loadWorkflowConfig();
        }

        // 更新流程选择（基于用户确认定制的阶段）
        async function updateProcessSelectionRadio() {
            try {
                const response = await fetch('/api/workflow-config');
                const configs = await response.json();
                
                // 只显示enable为true的流程
                const enabledWorkflows = configs.filter(config => config.enable);
                
                processSelectionRadio.innerHTML = '';
                
                if (enabledWorkflows.length === 0) {
                    processSelectionRadio.innerHTML = `
                        <div style="text-align: center; padding: 20px; color: #666;">
                            <p>暂无可用流程</p>
                        </div>
                    `;
                } else {
                    enabledWorkflows.forEach((config, index) => {
                        const radioItem = document.createElement('div');
                        radioItem.className = 'radio-item';
                        radioItem.innerHTML = `
                            <input type="radio" id="process_${index}" name="processSelection" value="${config.name}" ${index === 0 ? 'checked' : ''}>
                            <label for="process_${index}">${config.name}</label>
                        `;
                        processSelectionRadio.appendChild(radioItem);
                    });
                }
            } catch (error) {
                console.error('更新流程选择失败:', error);
            }
        }

        // 处理现有流程变化
        function handleExistingProcessChange(processName) {
            if (processName) {
                loadProcessDetails(processName);
            }
        }

        // 处理当前流程变化
        function handleCurrentProcessChange(processId) {
            if (processId) {
                // 重置流程状态（按钮和文本框）
                resetProcessState();
                
                // 清空结果区域
                resultSection.classList.add('hidden');
                bpmnContainer.innerHTML = '';
                sequenceTable.innerHTML = '';
            }
        }

        // 处理流程选择变化
        function handleProcessSelectionChange(processName) {
            if (processName) {
                // 重置流程状态（按钮和文本框）
                resetProcessState();
                
                // 清空结果区域
                resultSection.classList.add('hidden');
                bpmnContainer.innerHTML = '';
                sequenceTable.innerHTML = '';
            }
        }

        // 加载流程详情
        async function loadProcessDetails(processName) {
            try {
                const response = await fetch(`/api/processes/${processName}`);
                const process = await response.json();
                
                if (process.flowchart_svg && process.json_sequence_processed) {
                    displayResults(process.flowchart_svg, process.json_sequence_processed);
                }
            } catch (error) {
                console.error('加载流程详情失败:', error);
            }
        }

        // 运行流程
        async function runProcess() {
            if (isGenerating) return;
            
            const description = processDescription.value.trim();
            if (!description) {
                alert('请输入流程描述');
                return;
            }

            // 获取选中的流程
            const selectedProcess = document.querySelector('input[name="processSelection"]:checked') || 
                                   document.querySelector('input[name="currentProcess"]:checked');
            
            if (!selectedProcess || !selectedProcess.value) {
                alert('请选择一个流程');
                return;
            }

            // 检查是否切换了流程
            if (selectedProcessName && selectedProcessName !== selectedProcess.value) {
                // 清理旧流程的数据
                await clearProcessData(selectedProcessName);
                isFirstGeneration = true; // 切换流程时重置为首次生成状态
            }
            selectedProcessName = selectedProcess.value;

            isGenerating = true;
            runBtn.disabled = true;
            runBtn.innerHTML = '<span class="loading"></span> 生成中...';
            
            // 禁用其他阶段选择
            disableAllProcessSelections();

            try {
                if (isFirstGeneration) {
                    // 首次生成
                    const response = await fetch('/api/processes/generate-model', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            processId: selectedProcess.value,
                            description: description
                        })
                    });

                    const result = await response.json();
                    
                    if (result.success) {
                        // 获取流程数据
                        await loadProcessData(result.process_id);
                        runBtn.textContent = '更新';
                        runBtn.classList.add('update');
                        isFirstGeneration = false; // 标记为已生成
                    } else {
                        alert('生成失败: ' + result.message);
                    }
                } else {
                    // 更新模式
                    const response = await fetch('/api/processes/update-model', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            processId: selectedProcess.value,
                            description: description,
                            model: processModel,
                            feedbackHistory: feedbackHistory
                        })
                    });

                    const result = await response.json();
                    
                    if (result.success) {
                        // 获取更新后的流程数据
                        await loadProcessData(result.process_id);
                    } else {
                        alert('更新失败: ' + result.message);
                    }
                }
            } catch (error) {
                console.error('运行流程失败:', error);
                alert('运行流程失败');
            } finally {
                isGenerating = false;
                runBtn.disabled = false;
                if (runBtn.textContent !== '更新') {
                    runBtn.innerHTML = '运行';
                }
                
                // 重新启用所有阶段选择
                enableAllProcessSelections();
            }
        }

        // 清理流程数据
        async function clearProcessData(processId) {
            try {
                const response = await fetch(`/api/processes/clear-process/${processId}`, {
                    method: 'POST'
                });
                const result = await response.json();
                if (result.success) {
                    console.log(`已清理流程 ${processId} 的数据`);
                }
            } catch (error) {
                console.error('清理流程数据失败:', error);
            }
        }

        // 加载流程数据
        async function loadProcessData(processId) {
            try {
                const response = await fetch(`/api/processes/${processId}/data`);
                const result = await response.json();
                
                if (result.success) {
                    // 保存序列数据到全局变量
                    window.currentSequenceData = result.sequence;
                    
                    // 显示流程图和序列
                    displayResults(result.flowchart, result.sequence);
                    // 显示保存模型模块
                    showSaveModelModule();
                    console.log(`已加载流程 ${processId} 的数据，反馈数: ${result.feedback_count}`);
                } else {
                    console.error('加载流程数据失败:', result.message);
                }
            } catch (error) {
                console.error('加载流程数据失败:', error);
            }
        }

        // 显示参数配置模块

        // 显示保存模型模块
        function showSaveModelModule() {
            const saveModelModule = document.getElementById('saveModelModule');
            saveModelModule.style.display = 'block';
        }

        // 保存模型
        async function saveModel() {
            const saveBtn = document.getElementById('saveModelBtn');
            const saveStatus = document.getElementById('saveStatus');
            
            try {
                saveBtn.disabled = true;
                saveBtn.textContent = '保存中...';
                saveStatus.innerHTML = '';
                
                // 获取当前流程数据
                const selectedProcess = document.querySelector('input[name="processSelection"]:checked');
                if (!selectedProcess) {
                    throw new Error('请先选择一个流程');
                }
                
                const processId = selectedProcess.value;
                
                // 调用保存API
                const response = await fetch('/api/processes/save-model', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        processId: processId
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    saveStatus.innerHTML = '<span style="color: green;">✅ 模型保存成功！</span>';
                    // 刷新流程列表
                    loadExistingProcesses();
                } else {
                    saveStatus.innerHTML = `<span style="color: red;">❌ 保存失败: ${result.message}</span>`;
                }
                
            } catch (error) {
                console.error('保存模型失败:', error);
                saveStatus.innerHTML = `<span style="color: red;">❌ 保存失败: ${error.message}</span>`;
            } finally {
                saveBtn.disabled = false;
                saveBtn.textContent = '确认保存模型';
            }
        }

        // 显示结果
        function displayResults(flowchartData, sequenceData) {
            // 显示BPMN流程图
            if (typeof flowchartData === 'string' && flowchartData.includes('<svg')) {
                // 如果是SVG字符串，直接显示
                bpmnContainer.innerHTML = flowchartData;
            } else {
                // 如果是流程图数据，显示简单流程图
                displayFlowchart(flowchartData);
            }
            
            // 显示序列和参数配置并行布局（在确认模型模块上方）
            displaySequenceAndParams(sequenceData);
            
            // 显示结果区域
            resultSection.classList.remove('hidden');
        }

        // 显示流程图
        function displayFlowchart(data) {
            bpmnContainer.innerHTML = '';
            
            const flowchart = document.createElement('div');
            flowchart.className = 'flowchart';
            
            // 开始节点
            const startNode = document.createElement('div');
            startNode.className = 'flowchart-node';
            startNode.innerHTML = `
                <div class="node-circle node-start">1</div>
                <div>start</div>
            `;
            flowchart.appendChild(startNode);
            
            // 流程节点
            if (data && data.nodes) {
                data.nodes.forEach((node, index) => {
                    const arrow = document.createElement('div');
                    arrow.className = 'arrow';
                    flowchart.appendChild(arrow);
                    
                    const nodeElement = document.createElement('div');
                    nodeElement.className = 'flowchart-node';
                    nodeElement.innerHTML = `
                        <div class="node-rect">${node.name}</div>
                    `;
                    flowchart.appendChild(nodeElement);
                });
            }
            
            // 结束节点
            const endArrow = document.createElement('div');
            endArrow.className = 'arrow';
            flowchart.appendChild(endArrow);
            
            const endNode = document.createElement('div');
            endNode.className = 'flowchart-node';
            endNode.innerHTML = `
                <div class="node-circle node-end">end</div>
            `;
            flowchart.appendChild(endNode);
            
            bpmnContainer.appendChild(flowchart);
        }

        // 显示序列和参数配置并行布局
        function displaySequenceAndParams(data) {
            // 创建并行布局容器
            const sequenceAndParamsContainer = document.createElement('div');
            sequenceAndParamsContainer.className = 'sequence-and-params';
            
            // 创建序列容器
            const sequenceContainer = document.createElement('div');
            sequenceContainer.className = 'sequence-container';
            sequenceContainer.innerHTML = '<h4>流程序列表</h4>';
            
            // 创建序列表
            const sequenceTable = document.createElement('table');
            sequenceTable.className = 'sequence-table';
            sequenceTable.innerHTML = `
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>当前状态</th>
                        <th>下一状态</th>
                        <th>条件</th>
                        <th>参数</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            
            // 填充序列表数据
            if (Array.isArray(data)) {
                data.forEach((row, index) => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${row.id || index}</td>
                        <td>${row.now_state || ''}</td>
                        <td>${row.next_state || ''}</td>
                        <td>${typeof row.condition === 'object' ? JSON.stringify(row.condition) : (row.condition || '无')}</td>
                        <td>${typeof row.parameter === 'object' ? JSON.stringify(row.parameter) : (row.parameter || '无参数')}</td>
                    `;
                    sequenceTable.querySelector('tbody').appendChild(tr);
                });
            }
            
            // 将序列表添加到序列容器中
            const sequenceContent = document.createElement('div');
            sequenceContent.appendChild(sequenceTable);
            sequenceContainer.appendChild(sequenceContent);
            
            // 创建参数配置容器
            const paramsContainer = document.createElement('div');
            paramsContainer.className = 'params-container';
            paramsContainer.innerHTML = '<h4>参数配置</h4>';
            
            // 提取参数并创建参数配置界面
            const params = extractParameters(data);
            if (params.length === 0) {
                paramsContainer.innerHTML += '<div>无参数配置</div>';
            } else {
                params.forEach(param => {
                    const paramRow = document.createElement('div');
                    paramRow.className = 'param-row';
                    paramRow.innerHTML = `
                        <div class="param-label">${param.name}:</div>
                        <div class="param-input-group">
                            <input type="number" class="param-input" id="param_${param.name}" value="${param.value}" min="1">
                            <span class="param-unit">${param.unit}</span>
                        </div>
                        <button class="param-confirm-btn" onclick="updateParameter('${param.name}', '${param.originalKey}')">确认</button>
                    `;
                    paramsContainer.appendChild(paramRow);
                });
            }
            
            // 组装布局
            sequenceAndParamsContainer.appendChild(sequenceContainer);
            sequenceAndParamsContainer.appendChild(paramsContainer);
            
            // 替换原来的序列表
            const existingSequence = document.querySelector('.sequence-and-params');
            if (existingSequence) {
                existingSequence.remove();
            }
            
            // 找到原来的序列表并替换
            const oldSequenceTable = document.querySelector('#sequenceTable');
            if (oldSequenceTable && oldSequenceTable.parentNode) {
                // 替换原来的序列表
                oldSequenceTable.parentNode.replaceChild(sequenceAndParamsContainer, oldSequenceTable);
            } else {
                // 如果没找到，插入到确认模型模块之前
                const saveModelModule = document.querySelector('#saveModelModule');
                if (saveModelModule && saveModelModule.parentNode) {
                    saveModelModule.parentNode.insertBefore(sequenceAndParamsContainer, saveModelModule);
                } else {
                    // 如果都没找到，添加到结果区域
                    const resultSection = document.querySelector('#resultSection');
                    if (resultSection) {
                        resultSection.appendChild(sequenceAndParamsContainer);
                    }
                }
            }
        }
        
        // 提取参数
        function extractParameters(data) {
            const params = [];
            
            if (Array.isArray(data)) {
                data.forEach(row => {
                    if (row.parameter && typeof row.parameter === 'object') {
                        Object.keys(row.parameter).forEach(key => {
                            const value = row.parameter[key];
                            // 提取数字部分和单位
                            const match = value.toString().match(/(\d+)(.*)/);
                            if (match) {
                                params.push({
                                    name: key,
                                    value: match[1], // 数字部分
                                    unit: match[2],  // 单位部分（从原值中提取）
                                    originalKey: key,
                                    fullValue: value // 完整值，用于更新
                                });
                            }
                        });
                    }
                });
            }
            
            // 去重
            const uniqueParams = [];
            const seen = new Set();
            params.forEach(param => {
                if (!seen.has(param.name)) {
                    seen.add(param.name);
                    uniqueParams.push(param);
                }
            });
            
            return uniqueParams;
        }
        
        // 更新参数
        function updateParameter(paramName, originalKey) {
            const input = document.getElementById(`param_${paramName}`);
            const newValue = input.value;
            
            if (!newValue || newValue < 1) {
                alert('请输入有效的数值（大于0）');
                return;
            }
            
            // 更新内存中的序列数据
            if (window.currentSequenceData) {
                // 从参数配置界面中获取原始单位（从显示的单位文本中获取）
                const unitElement = input.parentNode.querySelector('.param-unit');
                const paramUnit = unitElement ? unitElement.textContent : '';
                
                // 更新所有包含该参数的行
                window.currentSequenceData.forEach(row => {
                    if (row.parameter && typeof row.parameter === 'object' && row.parameter[originalKey]) {
                        // 使用从界面获取的单位
                        row.parameter[originalKey] = newValue + paramUnit;
                    }
                });
                
                // 同步更新后端内存存储
                updateBackendSequenceData(window.currentSequenceData);
                
                // 重新显示序列表
                displaySequenceAndParams(window.currentSequenceData);
                
                alert(`参数 ${paramName} 已更新为 ${newValue}${paramUnit}`);
            }
        }
        
        // 同步更新后端内存存储
        async function updateBackendSequenceData(sequenceData) {
            try {
                const selectedProcess = document.querySelector('input[name="processSelection"]:checked');
                if (!selectedProcess) return;
                
                const processId = selectedProcess.value;
                
                // 调用后端API更新序列数据
                const response = await fetch(`/api/processes/${processId}/update-sequence`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        sequence: sequenceData
                    })
                });
                
                if (!response.ok) {
                    console.error('更新后端序列数据失败');
                }
            } catch (error) {
                console.error('同步更新后端存储失败:', error);
            }
        }
        
        // 显示序列表（保留原函数用于兼容）
        function displaySequenceTable(data) {
            // 保存当前序列数据
            window.currentSequenceData = data;
            displaySequenceAndParams(data);
        }
    </script>
</body>
</html>
